package mobilesearch.thread;

import java.util.ArrayList;

import mobilesearch.data.AlarmData;
import mobilesearch.ui.BroadcastCommand;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.text.format.DateUtils;

public class AlarmSearchThread extends Thread {

	private static final String TAG = "AlarmSearchThread";
	private ContentResolver resolver;
	private Context context;
	
	public AlarmSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		super.run();
		
		ArrayList<AlarmData> alarmList = new ArrayList<AlarmData>();
		try{
			Cursor cursor = this.resolver.query(Uri.parse("content://com.android.alarmclock/alarm"), null, null, null, null);
			if(cursor.moveToFirst()){
				do{
					AlarmData data = new AlarmData();
					int timeIndex = cursor.getColumnIndex("alarmtime");
					String time = cursor.getString(timeIndex);
					Log.i(TAG, time);
					
					int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR;
					String dateTime = DateUtils.formatDateTime(this.context, Long.valueOf(time),flags);
					
					data.setAlarmTime(dateTime);
					
					int msgIndex = cursor.getColumnIndex("message");
					String msg = cursor.getString(msgIndex);
					Log.i(TAG, msg);
					
					data.setAlarmMsg(msg);
					
					alarmList.add(data);
				}while(cursor.moveToNext());	
			}

		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}
		
		//broadcast the alarm data
		if(!alarmList.isEmpty()){
			Intent alarmIntent = new Intent(BroadcastCommand.SEARCH_ALARM);
			alarmIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_ALARM, alarmList);
			this.context.sendBroadcast(alarmIntent);	
		}
	}

}
